package service

import (
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"sort"
)

var GoodsMenuListCache = map[int][]*entity.GoodsCategory{}

// GetGoodsMenuList 返回在售的商品菜单列表
func GetGoodsMenuList(shopId int) []*entity.GoodsCategory {
	if menus, ok := GoodsMenuListCache[shopId]; menus != nil && ok {
		return menus
	}

	return GetGoodsMenuListFromDB(shopId)
}

func GetGoodsMenuListFromDB(shopId int) []*entity.GoodsCategory {
	goodsList := make([]*entity.Goods, 0)
	dao.GetDB().Table(entity.TableNameGoods).Where("shop_id=? and status=?", shopId, constant.GoodsStatusOnSell).Find(&goodsList)

	// 菜单分类, 关联类别和商品
	categoryList := make([]*entity.GoodsCategory, 0)
	dao.GetDB().Table(entity.TableNameGoodsCategory).Where("shop_id=? and show_status=true", shopId).Find(&categoryList)
	categoryMap := map[int]*entity.GoodsCategory{}
	for _, category := range categoryList {
		categoryMap[category.Id] = category
		category.GoodsList = make([]*entity.Goods, 0)
		for _, goods := range goodsList {
			goods.Count = 999
			if goods.GoodsCategoryId == category.Id {
				goods.GoodsCategoryName = category.Name
				goods.ParsePropertyList() // 反序列化属性列表
				category.GoodsList = append(category.GoodsList, goods)
			}
		}
		sort.Slice(category.GoodsList, func(a, b int) bool { return category.GoodsList[b].DisplayOrder > category.GoodsList[a].DisplayOrder })
	}
	sort.Slice(categoryList, func(a, b int) bool { return categoryList[b].DisplayOrder > categoryList[a].DisplayOrder })

	// 店铺热销-topk
	shopInfo := GetShopInfo(shopId)
	if shopInfo.FlagShowShopPopularGoods {
		list := make([]*entity.Goods, 0, len(goodsList))
		// 过滤掉不显示的种类
		for _, goods := range goodsList {
			if categoryMap[goods.GoodsCategoryId] != nil {
				list = append(list, goods)
			}
		}
		sort.Slice(list, func(i, j int) bool {
			// 销售额一样时价格越低排前面
			if list[j].SoldCount == list[i].SoldCount {
				return list[j].Price > list[i].Price
			}
			return list[i].SoldCount > list[j].SoldCount
		})
		count := int(shopInfo.ShopPopularGoodsMaxNum)
		if count > len(list) {
			count = len(list)
		}
		popularGoods := &entity.GoodsCategory{
			Id:           -10000,
			ShopId:       shopId,
			Name:         "店铺热销",
			DisplayOrder: -10000,
			ShowStatus:   true,
			GoodsList:    list[:count],
		}
		return append([]*entity.GoodsCategory{popularGoods}, categoryList...)
	}
	return categoryList
}

func GetGoodsById(goodsId int64) *entity.Goods {
	goods := entity.Goods{}
	dao.GetDB().Model(&goods).Where("id", goodsId).Take(&goods)
	goods.ParsePropertyList()
	return &goods
}
